define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        chat_info: function () {
            // 初始化表格参数配置
            var socket; //websocket的实例
            var lockReconnect = false; //避免重复连接
            reconnect();
            var from_id = Config.from_id;
            var type = 0;
            var select_type = 0;
            var school_id = Config.school_id;
            function getwebsocket() { //新建websocket的函数 页面初始化 断开连接时重新调用
           //    var wsUrl = 'ws://47.104.75.239:8282';
             //   var wsUrl = 'wss://ws.gkzzd.cn/wss';
                var wsUrl = 'wss://testws.gkzzd.cn/wss';
                socket = new WebSocket(wsUrl);
                socket.onerror = function (event) {
                    //console.log('websocket服务出错了');
                    reconnect(wsUrl);
                };
                socket.onclose = function (event) {
                    //console.log('websocket服务关闭了');
                    reconnect(wsUrl);
                };
                socket.onopen = function (event) {
                    heartCheck.reset().start(); //传递信息
                };

                socket.onmessage = function (event) {
                    var message = eval("(" + event.data + ")");
                    console.log(message);
                    switch (message.type) {  //用户绑定
                        case  "init":
                            var bild = '{"type":"bind","is_wx":"1","from_id":"' + from_id + '"}';
                            socket.send(bild);
                            list(from_id,type,select_type);
                            return;
                        // case  "bind":
                        //     var bild = '{"type":"online","from_id":' + from_id + '}';
                        //     socket.send(bild);
                        //     list(from_id,type);
                        //     return;
                        //     break;
                        case "text":  //对方消息发送到时
                            console.log(message);
                            timeoutID = window.setTimeout(function () {
                                list(from_id,type,select_type);
                                message_load(from_id, message.from_id, message.to_id, message.school_id);
                            }, 300);
                            //   $(".chat-fui-content").html("");


                            return;
                        case "save":  //发送的消息需要保存
                            // message.school_id = school_id;
                            // message.from_id =message.fromid;
                            // message.to_id =message.toid;
                            // message.type =1;
                            save_message(message);
                            timeoutID = window.setTimeout(function () {
                                list(from_id,type,select_type);
                                message_load(from_id, message.from_id, message.to_id, message.school_id);
                            }, 300);

                            return;
                        case "say_img":  //发送图片预留字段
                            list(from_id,type,select_type);
                            return;

                    }
                    heartCheck.reset().start();
                };
            }

            //enter，默认发送消息
            $(document).keydown(function (event) {
                console.log(event.keyCode);
                if (event.keyCode == 13) {
                    $('.btn-send').triggerHandler('click');
                    //取消回车默认换行
                    event.returnValue = false;
                    return false;
                }
            });
            $('.btn-send').off('click');
            $('.btn-send').unbind('click').click(function (even) {
                click();
            });

            //发送消息ws
            function click() {
                var text2 = document.getElementsByClassName('bosschat-chat-input');  //获取div值
                var text = text2[0].innerHTML;
                console.log(text);
                //  var text = $('.bosschat-chat-input').val();
                var div = document.querySelector('.conversation-bd-content'); //获取对应属性
                console.log(div.getAttribute('name'));
                var to_id = div.getAttribute('name');
                var from_id = Config.from_id;
                var school_id = Config.school_id;
                console.log(from_id);
                console.log(to_id);
                var message = '{"data":"' + text + '","type":"say","from_id":"' + from_id + '","to_id":"' + to_id + '","school_id":"' + school_id + '","msg_type":"1"}';
                socket.send(message);
                $('.bosschat-chat-input').html('');
            }

            //保存信息
            function save_message(message) {
                Fast.api.ajax({
                    url: 'cms/chat/save_message',
                    data: message
                }, function (data, ret) {

                    //成功的回调
                    return false;
                }, function (data, ret) {
                    console.log(data);
                    //失败的回调
                    Toastr.error(ret.msg);
                    return false;
                });
            }

            //获取当前用户的聊天列表
            function list(fromid,type,select_type) {
                Fast.api.ajax({
                    url: 'cms/chat/get_list',
                    data: {'to_id': fromid,'type':type,'select_type':select_type}
                }, function (data, ret) {
                    console.log(data);
                    // console.log(res);
                    var chant_data = data.data;
                    var translate = 0;
                    $(".geek-list-container").html('')
                    $.each(chant_data, function (index, content) {
                        // console.log(index);
                        // console.log(content);
                        // console.log(content.head_url);
                        if (content.countNoread == 0) {
                            var html = '<div data-v-6ebd3ff2="" data-index="'+index+'" data-school_id="' + content.school_id + '" data-new_from_id="' + content.from_id + '" data-from_id="' + fromid + '" data-new_to_id="' + content.to_id + '" class="geek-item" style="transform: translate(0px, ' + translate + 'px);">\n' +
                                '<div data-v-2471266b="" data-v-6ebd3ff2="" class="geek-item-warp geek-active" currentuid="86015123">\n' +
                                '<div data-v-2471266b="" class="figure"><img data-v-2471266b="" src="' + content.head_url + '">\n' +
                                '</div>\n' +
                                '<div data-v-2471266b="" class="text uid-86015123">\n' +
                                '<div data-v-2471266b="" class="title">\n' +
                                '<div data-v-2471266b="" class="user-operation">\n' +
                                '<span data-v-2471266b="" class="dots">...</span>\n' +
                                '</div>\n' +
                                '<span data-v-2471266b="" class="time">' + content.last_time + '</span>\n' +
                                '<span data-v-2471266b="" class="name">' + content.username + '</span>\n' +
                                '<p data-v-2471266b="" class="gray">\n' +
                                '<span data-v-2471266b="" class="push-text">' + content.last_message.content + '</span>\n' +
                                '</p>\n' +
                                '</div>\n' +
                                '</div>\n' +
                                '</div>\n' +
                                '</div>';
                            $(".geek-list-container").append(html);
                        } else {
                            var html = '<div data-v-6ebd3ff2="" data-index="' + index + '" class="geek-item" data-school_id="' + content.school_id + '"  data-new_from_id="' + content.from_id + '" data-from_id="' + fromid + '" data-new_to_id="' + content.to_id + '" style="transform: translate(0px, ' + translate + 'px);">\n' +
                                '<div data-v-2471266b="" data-v-6ebd3ff2="" class="geek-item-warp geek-active" currentuid="86015123">\n' +
                                ' <div data-v-2471266b="" class="figure"><img data-v-2471266b="" src="' + content.head_url + '">\n' +
                                '</div>\n' +
                                ' <div data-v-2471266b="" class="text uid-86015123">\n' +
                                '<div data-v-2471266b="" class="title">\n' +
                                '<div data-v-2471266b="" class="user-operation">\n' +
                                '<span data-v-2471266b="" class="dots">...</span>\n' +
                                '</div>\n' +
                                '<span data-v-2471266b="" class="time">' + content.last_time + '</span>\n' +
                                '<span data-v-2471266b="" class="name">' + content.username + '</span>\n' +
                                '<p data-v-2471266b="" class="gray">\n' +
                                '<span data-v-2471266b="" class="push-text">' + content.last_message.content + '</span>\n' +
                                '</p>\n' +
                                '</div>\n' +
                                '</div>\n' +
                                '</div>\n' +
                                '</div>';
                            $(".geek-list-container").append(html);

                        }
                        //每个对话框的高度
                        translate = translate + 76;
                        console.log(translate);
                    })
                    //成功的回调
                    return false;
                }, function (data, ret) {
                    console.log(data);
                    //失败的回调
                    Toastr.error(ret.msg);
                    return false;
                });

            }
            $(document).on("change", ".student_select", function () {
                //获取选中的value值
                var value = $(".student_select").val();
                list(from_id,0,value)  //看过我
            });
            //点击按钮跳转到左侧菜单
            $(document).on("click", ".all_people", function () {
                list(from_id,0,0)  //看过我
            });
            //点击按钮跳转到左侧菜单
            // $(document).on("click", ".look_me", function () {
            //     Backend.api.addtabs('cms/school/views_list','认证情况');
            //     // list(from_id,1,0)  //看过我
            // });
            //点击按钮跳转到左侧菜单
            $(document).on("click", ".say", function () {
                list(from_id,0,2)  //感兴趣的人
            });
            //点击按钮跳转到左侧菜单
            $(document).on("click", ".say_hello", function () {
                list(from_id,0,3)  //打招呼
            });
            //点击按钮跳转到左侧菜单
            $(document).on("click", ".say_ing", function () {
                list(from_id,0,0)  //沟通中
            });
            //点击按钮跳转到左侧菜单
            $(document).on("click", ".say_no", function () {
                list(from_id,0,4)  //不合适
            });
            //点击按钮跳转到左侧菜单
            $(document).on("click", ".follow", function () {
                list(from_id,0,5)  //收藏
            });

//消息记录列表
            function message_load(from_id, new_from_id, new_to_id, school_id) {
                Fast.api.ajax({
                    url: 'cms/chat/load',
                    data: {"from_id": new_from_id, "to_id": new_to_id, 'school_id': school_id, 'fromid': from_id}
                }, function (data, ret) {
                    console.log(data);
                    if(data.total == 0){
                        if(from_id == new_from_id){
                            var  to_id = new_to_id
                        }else{
                            var  to_id = new_from_id
                        }
                        var message = '{"data":"' + data.auto_message + '","type":"say","from_id":"' + from_id + '","to_id":"' + to_id + '","school_id":"' + school_id + '"}';
                        socket.send(message);
                    }
                    $('.bosschat-chat-list').html('');
                    var text = data.student.province + '·' + data.student.city + '·' + data.student.middle_school+ '·' + data.student.score1 + ' 联系方式：' + data.student.phone;
                    var html = '<div class="bosschat-geek-detail geek-chat-not" data-v-051e0979="">\n' +
                        '                                                <div class="bosschat-geek-card-top" data-v-051e0979=""><h3\n' +
                        '                                                        class="geek-name" data-v-051e0979="">'+data.student.nick_name+'</h3>\n'+
                        '                                                    <div class="bosschat-geek-right bosschat-goutong-job"\n' +
                        '                                                         data-v-051e0979="">\n'+
                        '                                                        <div class="popover popover-top-left">\n'+
                        '                                                        </div> <!----></div> <!----></div>\n' +
                        '                                                    <div class="bosschat-geek-job" data-v-051e0979=""><span\n' +
                        '                                                            class="card-brief-item" data-v-051e0979="">'+ text+'\n'+
                        '             </span></div> <!---->\n' +
                        '                                                    <div class="conversation-labels" data-v-051e0979=""\n' +
                        '                                                         data-v-6c03fb28="">\n' +
                        '                                                        <div class="bosschat-geek-tag" data-v-6c03fb28="">\n' +
                        '                                                            <div class="tag-ul" data-v-6c03fb28="">\n' +
                        '                                                                <div class="chat-labels-input" data-v-6c03fb28=""><span\n' +
                        '                                                                        class="btn-labels-entry" data-v-6c03fb28=""><img\n' +
                        '                                                                        alt=""\n' +
                        '                                                                        data-v-6c03fb28="" src="">'+data.student.candidates_identity+'</span></div>\n' +
                        '                                                            </div>\n' +
                        '                                                        </div> <!----> <!----></div> <!----></div>\n' +
                        '                                            </div>'
                    $('.bosschat-chat-list').append(html);
                    $.each(data.list, function (index, content) {
                        if (from_id == content.from_id) {
                            var  html = '<ul class="chat-message-ul">\n' +
                                ' <li id="temp-279493948551" timestamp="1650326550000" type="text"\n' +
                                'class="message item-friend status-read">\n' +
                                '<div class="message-time"><span class="time">' + content.createtime + '</span>\n' +
                                '</div>\n' +
                                '<div class="text1"><!----> <span>' + content.content + '</span>\n' +
                                '</div>\n' +
                                '</li>\n' +
                                '</ul>';
                            $('.bosschat-chat-list').append(html);
                        } else {
                            var   html = '<ul class="chat-message-ul">\n' +
                                ' <li id="temp-279493948551" timestamp="1650326550000" type="text"\n' +
                                'class="message item-friend status-read">\n' +
                                '<div class="message-time"><span class="time">' + content.createtime + '</span>\n' +
                                '</div>\n' +
                                '<div class="text"><!----> <span>' + content.content + '</span>\n' +
                                '</div>\n' +
                                '<div class="figure"><img\n' +
                                'src="' + content.head_url + '">\n' +
                                ' </div>\n' +
                                '</li>\n' +
                                '</ul>';

                            $('.bosschat-chat-list').append(html);
                            // $(".chat-content").append(' <div class="chat-text section-left flex"><span class="char-img" style="background-image: url('+to_head+')"></span> <span class="text"><i class="icon icon-sanjiao4 t-32"></i>'+replace_em(content.content)+'</span> </div>');

                        }

                    })
                    //始终下滑到最下端
                    var elem = document.getElementsByClassName('bosschat-chat-list')[0];
                    console.log(elem);
                    elem.scrollTop = elem.scrollHeight;
                    //成功的回调
                    return false;
                }, function (data, ret) {
                    console.log(data);
                    //失败的回调
                    Toastr.error(ret.msg);
                    return false;
                });
            }
            function reconnect(url) {
                if (lockReconnect) return;
                lockReconnect = true;
                //没连接上会一直重连，设置延迟避免请求过多
                setTimeout(function () {
                    getwebsocket();
                    lockReconnect = false;
                }, 2000);
            }

            //心跳检测
            var heartCheck = {
                timeout: 60000, //60秒
                timeoutObj: null,
                serverTimeoutObj: null,
                reset: function () {
                    clearTimeout(this.timeoutObj);
                    clearTimeout(this.serverTimeoutObj);
                    return this;
                },
                start: function () {
                    var self = this;
                    this.timeoutObj = setTimeout(function () {
                        //这里发送一个心跳，后端收到后，返回一个心跳消息，
                        //onmessage拿到返回的心跳就说明连接正常
                        socket.send("心跳测试");
                        self.serverTimeoutObj = setTimeout(function () { //如果超过一定时间还没重置，说明后端主动断开了
                            socket.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                        }, self.timeout);
                    }, this.timeout);
                }
            };
//点击左侧聊天框时
            $(document).on("click", ".geek-item", function () {
                var new_from_id = $(this).attr('data-new_from_id'); //聊天框的发送者id
                var from_id = $(this).attr('data-from_id');  //登录人的id
                var new_to_id = $(this).attr('data-new_to_id'); //聊天框的接收者id
                var school_id = $(this).attr('data-school_id');  //聊天框对应的学校
                var chat_people_id = new_from_id;
                if (new_from_id == from_id) {  //判断聊天详情页里面的to_id,始终让to_id为对方
                    chat_people_id = new_to_id;
                }

                $('.conversation-bd-content').attr('name', chat_people_id);
                $('.chat-weclcome-warp').hide();
                $('.conversation-main').show();
                $('.bosschat-chat-list').html("");
                message_load(from_id, new_from_id, new_to_id, school_id);
            });
            //查看结果

            function replace_em(str){

                str = str.replace(/\</g,'&lt;');

                str = str.replace(/\>/g,'&gt;');

                str = str.replace(/\n/g,'<br/>');

                str = str.replace(/\[em_([0-9]*)\]/g,'<img src="__STATIC__/qqFace/arclist/$1.gif" border="0" />');

                return str;

            }
        },
        create_chat: function () {
            Controller.api.bindevent();
            top.window.$(".sidebar-menu a[pinyin=liaotianguanli]").trigger("click")
        },
        log: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'cms/chat/log' + location.search,
                    // add_url: 'member/college/college_add',
                    // edit_url: 'member/college/college_edit',
                    // del_url: 'member/college/del',
                    // multi_url: 'member/college/multi',
                    table: 'college',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'school_id', title: __('学校ID')},
                        {field: 'from_id', title: __('发送人ID')},
                        {field: 'from_name', title: __('发送人昵称'),operate:false},
                        {field: 'to_id', title: __('接收人ID')},
                        {field: 'to_name', title: __('接收人昵称'),operate:false},
                      //  {field: 'content', title: __('内容'),operate:false},
                        {field: 'content', title: __('内容') , operate: false, cellStyle () {
                                return{
                                    css: {
                                        "width":"230px",
                                        "text-align": "left !important"
                                    }
                                };

                            }},
                        {field: 'createtime', title: __('发送时间'),operate:false,formatter: Table.api.formatter.datetime},
                        // {field: 'operate', title: __('Operate'), table: table, buttons: [
                        //      //   {name: 'send', text: __('view'), icon: 'fa fa-eye', classname: 'btn btn-xs btn-warning btn-dialog chakan', url: 'member/college/college_detail'},
                        //     ],  events: Table.api.events.operate, formatter: function (value, row, index) {
                        //         var that = $.extend({}, this);
                        //         $(table).data("operate-edit", true); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                        //         $(table).data("operate-del", null); // 列表页面隐藏 .编辑operate-edit  - 删除按钮operate-del
                        //         that.table = table;
                        //         return Table.api.formatter.operate.call(that, value, row, index);
                        //     }},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            $(document).on("click", ".btn-change", function () {
                Fast.api.open('cms/chat/change_log','转移聊天记录')
            });
        },
        change_log: function () {
            Controller.api.bindevent();
        },
        api: {

            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
        }
    };
    return Controller;
});
// $('.icon-emoji1').qqFace({
//
//     assign:'saytext',
//
//     path:'__STATIC__/qqFace/arclist/'	//表情存放的路径
//
// });
//
// $(".sub_btn").click(function(){
//
//     var str = $("#saytext").val();
//
//     $("#show").html(replace_em(str));
//
// });


// //消息记录列表
// function message_load(from_id, new_from_id, new_to_id, school_id) {
//     Fast.api.ajax({
//         url: 'cms/chat/load',
//         data: {"from_id": new_from_id, "to_id": new_to_id, 'school_id': school_id, 'fromid': from_id}
//     }, function (data, ret) {
//         console.log(data);
//         if(data.total == 0){
//             if(from_id == new_from_id){
//               var  to_id = new_to_id
//             }else{
//               var  to_id = new_from_id
//             }
//             var message = '{"data":"' + data.auto_message + '","type":"say","from_id":"' + from_id + '","to_id":"' + to_id + '","school_id":"' + school_id + '"}';
//             socket.send(message);
//         }
//         $('.bosschat-chat-list').html('');
//         var text = data.student.province + '·' + data.student.city + '·' + data.student.middle_school+ '·' + data.student.score1
//        var html = '<div class="bosschat-geek-detail geek-chat-not" data-v-051e0979="">\n' +
//             '                                                <div class="bosschat-geek-card-top" data-v-051e0979=""><h3\n' +
//             '                                                        class="geek-name" data-v-051e0979="">'+data.student.nick_name+'</h3>\n'+
//             '                                                    <div class="bosschat-geek-right bosschat-goutong-job"\n' +
//             '                                                         data-v-051e0979="">\n'+
//             '                                                        <div class="popover popover-top-left">\n'+
//                        '                                                        </div> <!----></div> <!----></div>\n' +
//             '                                                    <div class="bosschat-geek-job" data-v-051e0979=""><span\n' +
//             '                                                            class="card-brief-item" data-v-051e0979="">'+ text+'\n'+
//             '             </span></div> <!---->\n' +
//             '                                                    <div class="conversation-labels" data-v-051e0979=""\n' +
//             '                                                         data-v-6c03fb28="">\n' +
//             '                                                        <div class="bosschat-geek-tag" data-v-6c03fb28="">\n' +
//             '                                                            <div class="tag-ul" data-v-6c03fb28="">\n' +
//             '                                                                <div class="chat-labels-input" data-v-6c03fb28=""><span\n' +
//             '                                                                        class="btn-labels-entry" data-v-6c03fb28=""><img\n' +
//             '                                                                        alt=""\n' +
//             '                                                                        data-v-6c03fb28="" src="">'+data.student.candidates_identity+'</span></div>\n' +
//             '                                                            </div>\n' +
//             '                                                        </div> <!----> <!----></div> <!----></div>\n' +
//             '                                            </div>'
//         $('.bosschat-chat-list').append(html);
//         $.each(data.list, function (index, content) {
//             if (from_id == content.from_id) {
//                var  html = '<ul class="chat-message-ul">\n' +
//                     ' <li id="temp-279493948551" timestamp="1650326550000" type="text"\n' +
//                     'class="message item-friend status-read">\n' +
//                     '<div class="message-time"><span class="time">' + content.createtime + '</span>\n' +
//                     '</div>\n' +
//                     '<div class="text1"><!----> <span>' + content.content + '</span>\n' +
//                     '</div>\n' +
//                     '</li>\n' +
//                     '</ul>';
//                 $('.bosschat-chat-list').append(html);
//             } else {
//               var   html = '<ul class="chat-message-ul">\n' +
//                     ' <li id="temp-279493948551" timestamp="1650326550000" type="text"\n' +
//                     'class="message item-friend status-read">\n' +
//                     '<div class="message-time"><span class="time">' + content.createtime + '</span>\n' +
//                     '</div>\n' +
//                     '<div class="text"><!----> <span>' + content.content + '</span>\n' +
//                     '</div>\n' +
//                     '<div class="figure"><img\n' +
//                     'src="' + content.head_url + '">\n' +
//                     ' </div>\n' +
//                     '</li>\n' +
//                     '</ul>';
//
//                 $('.bosschat-chat-list').append(html);
//                 // $(".chat-content").append(' <div class="chat-text section-left flex"><span class="char-img" style="background-image: url('+to_head+')"></span> <span class="text"><i class="icon icon-sanjiao4 t-32"></i>'+replace_em(content.content)+'</span> </div>');
//
//             }
//
//         })
//         //始终下滑到最下端
//         var elem = document.getElementsByClassName('bosschat-chat-list')[0];
//         console.log(elem);
//         elem.scrollTop = elem.scrollHeight;
//         //成功的回调
//         return false;
//     }, function (data, ret) {
//         console.log(data);
//         //失败的回调
//         Toastr.error(ret.msg);
//         return false;
//     });
// }
//点击按钮跳转到左侧菜单
$(document).one("click", ".star-group", function () {
    top.window.$(".sidebar-menu a[pinyin=baokaokaosheng]").trigger("click")
});
